


import UIKit
import SnapKit

private let reuseIdentifier = "Cell"
private let column: CGFloat = 4
private let pictureCellMargin: CGFloat = 10

private let maxImageCount = 3

class PictureSelectorViewController: UICollectionViewController {
    
    //添加图片数组属性
    lazy var imageList = [UIImage]()
    
    init() {
        let layout = UICollectionViewFlowLayout()
        //设置 layout
        let w = (screenW - (column + 1) * pictureCellMargin) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        // 设置 section 间距
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        super.init(collectionViewLayout: layout)
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(PictureSelectorCell.self,forCellWithReuseIdentifier: reuseIdentifier)
    }
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return imageList.count + 1
        let delta = (imageList.count == maxImageCount) ? 0:1
        return imageList.count + delta
        
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        cell.selectorCellDelegate = self
        cell.backgroundColor = UIColor.randomColor()
        //绑定数据源
        if indexPath.item == imageList.count {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        return cell
    }
    
}

extension PictureSelectorViewController: PictureSelectorCellDelegate {
    func userWillAddPiccture(cell: PictureSelectorCell) {
        print("添加图片")
        //使用系统的图片选择器
        let picker = UIImagePickerController()
        //指定代理
        picker.delegate = self
        
        //设置是否允许编辑 在上传头像的时候 需要打开
//        picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    func userWillDeletePicture(cell: PictureSelectorCell) {
       //获取点击的 cell的 indexPath
        let indexPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indexPath!.item)
        
        //刷新视图,加上动画
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            cell.alpha = 0
            }) { (_) -> Void in
                cell.alpha = 1
             self.collectionView?.reloadData()
        }
    }
}

//遵守图片协议选择器的协议
extension PictureSelectorViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //开始添加图片
        imageList.append(image)
        //刷新视图合集
        collectionView?.reloadData()
        
        //一旦实现协议方法 dismiss 就交给程序员
        dismissViewControllerAnimated(true, completion: nil)
    }
}

@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    //定义协议方法
    //添加图片的协议方法
    optional func userWillAddPiccture(cell: PictureSelectorCell)
    
    //删除图片的协议方法
    optional func userWillDeletePicture(cell: PictureSelectorCell)
}


class PictureSelectorCell: UICollectionViewCell {
    //定义代理

    weak var selectorCellDelegate:PictureSelectorCellDelegate?
    
    @objc private func addBtnDidClick() {
        selectorCellDelegate?.userWillAddPiccture?(self)
    }
    @objc private func deleteBtnDidClick() {
        selectorCellDelegate?.userWillDeletePicture?(self)
    }
    //MARK: 3.重写父类的构造方法 调用设置UI
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 2.设置 UI
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleBtn)
        //设置约束
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        //添加事件
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    }
    var image: UIImage? {
        didSet{
            deleBtn.hidden = (image == nil)
            if image != nil {
                addBtn.setBackgroundImage(image, forState: .Normal)
            } else{
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState:UIControlState.Normal)
            }
            
        }
    }
    //MARK: 1. 懒加载所有子控件
    private lazy var addBtn: UIButton = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    private lazy var deleBtn: UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)
}

